<?
session_start();

require_once('./lib/oauth.class.php');
require_once('./lib/Config.php');
require_once('./lib/DB.gear.php');
require_once('./lib/lib.gear.php');
require_once('./lib/lib.garden.php');
require_once('./lib/people.class.php');
require_once('./lib/signup.class.php');

$_SESSION['callback_visit'] = 1;

// get authorization_code
$authorization_code = $_GET['code'];

//do_authorize($authorization_code);
$authorization = new mixi_auth;
$authorization->authorize($authorization_code);

$mixi_refresh_token = $authorization->get_refresh_token();
$mixi_access_token  = $authorization->get_access_token();

//set_tokens($access_token, $refresh_token);

$people = new People;
$people->set_access_token($authorization->get_access_token());
$people->get_profile();

$user_id       = $people->get_member_id();
$user_name     = $people->get_name();
$profile_image = $people->get_thumbnailUrl();

$url = 'http://reafo.net/garden/signup.php';
$data = array(
    'user_id'              => $user_id,
    'user_name'            => $user_name,
    'profile_image'        => $profile_image,
    'type'                 => 'mixi',
    'g_key_din39s03j23ogn' => G_KEY,
);

$headers = array(
    'Authorization: OAuth '.'todoke', 
);

$options = array('http' => array(
    'method' => 'POST',
    'content' => http_build_query($data),
    'header' => implode("\r\n", $headers),
));

$contents = file_get_contents($url, false, stream_context_create($options));

//preDump($contents);

$json_data = (json_decode($contents, true));

switch($json_data['status'])
{
    case 'login':
        set_session($json_data,$mixi_access_token, $mixi_refresh_token);
        header("HTTP/1.1 301 Moved Permanently");
        header("Location: http://reafo.net/garden/home.php");
    break;
    
    case 'signup':
        post($json_data['user_id'], 'started Garden', 0, $device = '', 1);
        set_session($json_data,$mixi_access_token, $mixi_refresh_token);
        header("HTTP/1.1 301 Moved Permanently");
        header("Location: http://reafo.net/garden/friends.php");
    break;
    
    case 'error':
        echo 'error';
    break;
}



/*
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://reafo.net/garden/next.php");
exit();
*/

?>
